<?php require_once('Connections/locamedicadmin.php'); ?>

<?php include('userValidation.php'); ?>

<?php

include('functions.php');

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {

	$errors = array();

	$csrenumber = $_POST['csre_number'];
	$keywords = $_POST['keywords'];
	$manufid = $_POST['manufacture_id'];
	$locamedicnum = $_POST['locamedic_number'];
	$name = $_POST['name_FR'];
	$categoryid = $_POST['category_id'];
	$price = $_POST['price'];
	$details = $_POST['details_FR'];
	$taxable = isset($_POST['taxable']) ? "true" : "";
	$manuf = $_POST['manufacture_num'];
	
	if (strlen($name) == 0) { array_push($errors,  "Nom ne peut pas etre vide"); } 
	
	if (strlen($price) == 0) { 
		array_push($errors,  "Prix ne peut pas etre vide"); 
	} else if (!is_numeric($price)) {
		array_push($errors,  "Prix doit etre un nombre"); 
	} else if ($price < 0) {
		array_push($errors,  "Prix doit etre positif"); 
	}
	
	$serviceselected = false;
	$keys_serv = array_keys($_POST);
	foreach ($keys_serv as $key) {
		if (!$serviceselected || strstr($key,"service_")) {
			$serviceselected = true;
		}
	}
	
	if (!$serviceselected) {
		array_push($errors,  "Au moins un service doit etre selectionne"); 
	}
	
	if (strlen($details) == 0) { array_push($errors, "Details ne peut pas etre vide"); } 
	
	if (sizeof($errors) == 0) {


		$filepdf = strtolower($_FILES["uploadpdf"]["name"]);
		$extpdf = strtolower(substr($filepdf,-3,3));
		$pdf = date("dmYHis").".".$extpdf;
		$target_path_pdf = "../pdf/" . $pdf; 
		
		if (!move_uploaded_file($_FILES['uploadpdf']['tmp_name'], $target_path_pdf)){
			$pdf = $_POST['lastpdf'];
		}
	
		$file = strtolower($_FILES["uploadimage"]["name"]);
		$ext = strtolower(substr($file,-3,3));
		$imagen = date("dmYHis").".".$ext;
		$target_path = "../images/csre/products/" . $imagen; 
		
		if(move_uploaded_file($_FILES['uploadimage']['tmp_name'], $target_path)) {
	
			include('SimpleImage.php');
	
			$image = new SimpleImage();
			$image->load($target_path);
			$ancho = $image->getWidth();
			$alto = $image->getHeight();
			if ($ancho > 640 || $alto > 480) {
				if ($ancho > $alto) {
					$alto = 640 * $alto / $ancho;
					$ancho = 640;
					echo 'ancho mas que alto';
				} else { 
					$ancho = 480 * $ancho / $alto;
					$alto = 480;
					echo 'alto mas que ancho';
				}
				$image->resize($ancho, $alto);
				$image->save($target_path);
			}
	
		} else {
			$imagen = $_POST['lastimage'];
		}
	
	  
	  
	  $updateSQL = sprintf("UPDATE csre_product SET csre_number=%s, keywords=%s, manufacture_id=%s, 
		locamedic_number=%s, name_FR=%s, name_US=%s, category_id=%s, price=%s, details_FR=%s, details_US=%s, taxable=%s, image=%s, show_image=%s,
		pdf = %s, show_pdf = %s, manufacture_num = %s	WHERE product_id=%s",
						   GetSQLValueString($_POST['csre_number'], "text"),
						   GetSQLValueString($_POST['keywords'], "text"),
						   GetSQLValueString($_POST['manufacture_id'], "int"),
						   GetSQLValueString($_POST['locamedic_number'], "text"),
						   GetSQLValueString($_POST['name_FR'], "text"),
						   GetSQLValueString(" ", "text"),
						   GetSQLValueString($_POST['category_id'], "int"),
						   GetSQLValueString($_POST['price'], "double"),
						   GetSQLValueString($_POST['details_FR'], "text"),
						   GetSQLValueString(" ", "text"),
						   GetSQLValueString(isset($_POST['taxable']) ? "true" : "", "defined","1","0"),
						   GetSQLValueString($imagen, "text"),
						   GetSQLValueString(isset($_POST['show_image']) ? "true" : "", "defined","1","0"),
						   GetSQLValueString($pdf, "text"),
						   GetSQLValueString(isset($_POST['show_pdf']) ? "true" : "", "defined","1","0"),
						   GetSQLValueString($_POST['manufacture_num'], "text"),
						   GetSQLValueString($_POST['product_id'], "int"));
	
		echo ($updateSQL);
	
		$keys = array_keys($_POST);
	
		$deleteProductService = sprintf("delete from csre_prod_service where product_id = %s ", $_POST['product_id']);
		mysql_select_db($database_locamedicadmin, $locamedicadmin);
		mysql_query($deleteProductService, $locamedicadmin) or die(mysql_error());
		
		foreach ($keys as $key) {
			if (strstr($key,"service_")) {
				$serviceid = str_replace("service_","", $key);
				$insertSqlService = sprintf("INSERT INTO csre_prod_service (type_id, product_id) VALUES (%s, %s)", $serviceid, $_POST['product_id']);
				mysql_select_db($database_locamedicadmin, $locamedicadmin);
				$Result1 = mysql_query($insertSqlService, $locamedicadmin) or die(mysql_error());
			}
		}	
	
	
	  mysql_select_db($database_locamedicadmin, $locamedicadmin);
	  $Result1 = mysql_query($updateSQL, $locamedicadmin) or die(mysql_error());
	
	  $updateGoTo = "product_list.php";
	  if (isset($_SERVER['QUERY_STRING'])) {
		$updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
		$updateGoTo .= $_SERVER['QUERY_STRING'];
	  }
	
		header(sprintf("Location: %s", $updateGoTo));
	
	}	 
  
}

$colname_product = "-1";
if (isset($_GET['productid'])) {
  $colname_product = (get_magic_quotes_gpc()) ? $_GET['productid'] : addslashes($_GET['productid']);
}
mysql_select_db($database_locamedicadmin, $locamedicadmin);
$query_product = sprintf("SELECT * FROM csre_product WHERE product_id = %s", $colname_product);
$product = mysql_query($query_product, $locamedicadmin) or die(mysql_error());
$row_product = mysql_fetch_assoc($product);
$totalRows_product = mysql_num_rows($product);

mysql_select_db($database_locamedicadmin, $locamedicadmin);
$query_manufacturelist = "SELECT * FROM csre_manufacture order by name_FR";
$manufacturelist = mysql_query($query_manufacturelist, $locamedicadmin) or die(mysql_error());
$row_manufacturelist = mysql_fetch_assoc($manufacturelist);
$totalRows_manufacturelist = mysql_num_rows($manufacturelist);

mysql_select_db($database_locamedicadmin, $locamedicadmin);
$query_categorylist = "SELECT * FROM csre_category order by name_FR";
$categorylist = mysql_query($query_categorylist, $locamedicadmin) or die(mysql_error());
$row_categorylist = mysql_fetch_assoc($categorylist);
$totalRows_categorylist = mysql_num_rows($categorylist);

mysql_select_db($database_locamedicadmin, $locamedicadmin);
$query_service = "SELECT * FROM csre_serv_types";
$service = mysql_query($query_service, $locamedicadmin) or die(mysql_error());
$row_service = mysql_fetch_assoc($service);
$totalRows_service = mysql_num_rows($service);


?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Locamedic CSRE Admin</title>
<link href="locamedicadmin.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="page">

	<?php include('sidebar.php'); ?>
	
	<!-- end sidebar -->
	<div id="content">
		<div align="center"><img src="images/page_image_5.jpg" alt="" /></div>
	  <div class="boxed">
			<h1 class="title2">Modifier le produit</h1>
			
			<?php include('errors.php'); ?>
	  
            <form enctype="multipart/form-data" method="post" name="form1" action="<?php echo $editFormAction; ?>">
              <table>
                <tr valign="baseline">
                  <td nowrap >CSRE #:</td>
                  <td><input type="text" name="csre_number" value="<?php echo getValorReg('csre_number', $row_product); ?>" size="32"></td>
                </tr>
                <tr valign="baseline">
                  <td nowrap >Keywords:</td>
                  <td><input type="text" name="keywords" value="<?php echo getValorReg('keywords', $row_product); ?>" size="32"></td>
                </tr>
                <tr valign="baseline">
                  <td nowrap >Manufacture:</td>
                  <td> 
				  	<select name="manufacture_id">
				      <?php do {  ?>
				      	<option value="<?php echo $row_manufacturelist['manufacture_id']?>"
							<?php if (getValorReg('manufacture_id', $row_product)==$row_manufacturelist['manufacture_id']) { echo "selected=\"selected\"";}?> >
							<?php echo $row_manufacturelist['name_' . $lang]?>
						</option>
				      <?php } while ($row_manufacturelist = mysql_fetch_assoc($manufacturelist)); ?>
                    </select>
                  </td>
                </tr>
                <tr valign="baseline">
                  <td nowrap >Locamedic #:</td>
                  <td><input type="text" name="locamedic_number" value="<?php echo getValorReg('locamedic_number', $row_product); ?>" size="32"></td>
                </tr>
                <tr valign="baseline">
                  <td nowrap >Name:</td>
                  <td><input type="text" name="name_FR" value="<?php echo getValorReg('name_FR', $row_product); ?>" size="32"></td>
                </tr>
                <tr valign="baseline">
                  <td nowrap >Category:</td>
                  	<td>
						<select name="category_id">
						<?php do {  ?>
							<option value="<?php echo $row_categorylist['category_id']?>" 
								<?php if (getValorReg('category_id', $row_product) == $row_categorylist['category_id']) { echo "selected=\"selected\""; }  ?> >
								<?php echo $row_categorylist['name_' . $lang]?>
							</option>
						<?php } while ($row_categorylist = mysql_fetch_assoc($categorylist)); ?>
						</select>
					</td>
                </tr>
				<tr valign="baseline">
                  <td nowrap >Manufacture #:</td>
                  <td><input type="text" name="manufacture_num" value="<?php echo getValorReg('manufacture_num', $row_product); ?>" size="32"></td>
                </tr>
                <tr valign="baseline">
                  <td nowrap >Price:</td>
                  <td><input type="text" name="price" value="<?php echo getValorReg('price', $row_product); ?>" size="32"></td>
                </tr>
				<tr>
					<td>
						Taxable:
					</td>
					<td>
						<input type="checkbox" name="taxable" value="1" 
							<?php 
								if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
									if (getValor('taxable') == 1) { echo "checked='checked'"; } 								
								} else {
									if (getValorReg('taxable', $row_product) == 1) { echo "checked='checked'"; } 								
								}
							?> 
						/>
					</td>
				</tr>
                <tr valign="baseline">
                  <td nowrap >Details:</td>
                  <td><textarea type="text" name="details_FR" size="32"><?php echo getValorReg('details_FR', $row_product); ?></textarea></td>
                </tr>
				<tr>
					<td>Service</td>
					<td>
						<table>
						  <?php 
						  	
							mysql_select_db($database_locamedicadmin, $locamedicadmin);
							$query_service_product = "SELECT type_id FROM csre_prod_service WHERE product_id = " . $row_product['product_id'];
							$service_product = mysql_query($query_service_product, $locamedicadmin) or die(mysql_error());
							$row_service_product = mysql_fetch_assoc($service_product);
							$totalRows_service_product = mysql_num_rows($service_product);
							
							$servicearray = array();
						
							if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
								$keys_serv = array_keys($_POST);
								foreach ($keys_serv as $key) {
									if (strstr($key,"service_")) {
										$tid = str_replace("service_", "", $key);
										array_push($servicearray, $tid);
									}
								}
							} else {
								do {  
								  array_push($servicearray, $row_service_product['type_id']);
								} while ($row_service_product = mysql_fetch_assoc($service_product));
							}
							
							do {
							
							?>
							<tr>
								<td>
									<input 
										type="checkbox" 
										name="service_<?php echo $row_service['type_id']?>"
										<?php 
											foreach ($servicearray as $value) {
												if ($value == $row_service['type_id']) {
													echo "checked='checked'";
												}
											}
										?> />
								</td>
								<td><?php echo $row_service['description']?></td>
							</tr>

						  <?php } while ($row_service = mysql_fetch_assoc($service)); ?>
						</table>
					</td>
				</tr>
				
				<tr>
					<td align="left">Image</td>
					<td><input type="file" name="uploadimage" /></td>
				</tr>
				
				<tr>
					<td>
						Montrer l'image
					</td>
					<td>
						<input type="checkbox" value="1" name="show_image" 
							<?php 
								if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
									if (getValor('show_image') == 1) { echo "checked='checked'"; } 								
								} else {
									if (getValorReg('show_image', $row_product) == 1) { echo "checked='checked'"; } 								
								}
							?>
						/>
					</td>
				</tr>
				
				<tr>
					<td align="left">PDf</td>
					<td><input type="file" name="uploadpdf" /></td>
				</tr>
				
				<tr>
					<td>
						Montrer l'pdf
					</td>
					<td>
						<input type="checkbox" value="1" name="show_pdf" 
							<?php 
								if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
									if (getValor('show_pdf') == 1) { echo "checked='checked'"; } 								
								} else {
									if (getValorReg('show_pdf', $row_product) == 1) { echo "checked='checked'"; } 								
								}
							?>
						/>
					</td>
				</tr>
                
              </table>
              
			  <input type="hidden" name="lastimage" value="<?php echo $row_product['image'];  ?>"  />
			  <input type="hidden" name="lastpdf" value="<?php echo $row_product['pdf'];  ?>"  />			  
			  
			  <div class="botonera">
			  	<input type="submit" value="Enregister">
				<input type="button" onclick="if (confirm('Etes-vous sur de vouloir annuler?')) { window.location='product_list.php' }" value="Annuler" />
			  </div>
			  
			  <input type="hidden" name="MM_update" value="form1">
              <input type="hidden" name="product_id" value="<?php echo $row_product['product_id']; ?>">
			  
            </form>
            <p>&nbsp;</p>
	  </div>
  </div>
	<!-- end content -->
	<div style="clear: both;">&nbsp;</div>
</div>
<!-- end page -->

<?php include('footer.php'); ?>

</body>
</html>
<?php
mysql_free_result($product);
mysql_free_result($manufacturelist);
mysql_free_result($categorylist);
?>
